from fastapi import APIRouter, HTTPException, status, Depends
from typing import List, Optional
from pydantic import BaseModel
from app.services.example_service import example_service, ExampleItem
from app.services.user import UserService

router = APIRouter()


class UserCreate(BaseModel):
    """创建用户的请求模型"""
    username: str
    password: str
    email: str
    note: Optional[str] = None


class ItemUpdate(BaseModel):
    """更新项目的请求模型"""
    name: Optional[str] = None
    value: Optional[float] = None
    description: Optional[str] = None

@router.get("/uesrs")
async def get_items():
    """获取所有用户"""

    return await UserService.get_all_users()


@router.get("/items/{item_id}", response_model=ExampleItem)
async def get_item(item_id: int):
    """根据ID获取项目"""
    try:
        return example_service.get_by_id(item_id)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))


@router.post("/uesr", status_code=status.HTTP_201_CREATED)
async def create_item(item: UserCreate):
    """创建新用户"""
    return await UserService.create_user(
        username=item.username,
        password_hash=item.password,
        email=item.email,
        note=item.note
    )


@router.put("/items/{item_id}", response_model=ExampleItem)
async def update_item(item_id: int, item: ItemUpdate):
    """更新项目"""
    try:
        return example_service.update(
            item_id=item_id,
            name=item.name,
            value=item.value,
            description=item.description
        )
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))


@router.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
    """删除项目"""
    try:
        example_service.delete(item_id)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))